<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="套餐分类" prop="categoryId">
        <el-select v-model="queryParams.categoryId" placeholder="请选择套餐分类" clearable @change="handleQuery">
          <el-option v-for="category in categoryList" :key="category.id" :label="category.name" :value="category.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="套餐名称" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入套餐名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="售卖状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择售卖状态" clearable>
          <el-option v-for="dict in dict.type.steal_status" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['merchant:setmeal:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['merchant:setmeal:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['merchant:setmeal:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['merchant:setmeal:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="setmealList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="主键" align="center" prop="id" /> -->
      <el-table-column label="套餐名称" align="center" prop="name" />
      <el-table-column label="套餐图片" align="center" prop="image" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.image" :width="50" :height="50" />
        </template>
      </el-table-column>
      <!-- <el-table-column label="套餐分类" align="center" prop="categoryId" /> -->
      <el-table-column label="套餐分类" align="center">
        <template slot-scope="scope">
          {{ getCategoryName(scope.row.categoryId) }}
        </template>
      </el-table-column>
      <!-- <el-table-column label="套餐价" align="center" prop="price" /> -->
      <el-table-column label="套餐价" align="center" prop="price">
        <template slot-scope="scope">
          ￥{{ scope.row.price }}
        </template>
      </el-table-column>
      <el-table-column label="售卖状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.steal_status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="最后操作时间" align="center" prop="updateTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="handleUpdate(scope.row)"
            v-hasPermi="['merchant:setmeal:edit']">修改</el-button>
          <el-button size="mini" type="text" @click="handleDelete(scope.row)"
            v-hasPermi="['merchant:setmeal:remove']">删除</el-button>
          <el-button size="mini" type="text" @click="toggleStatus(scope.row)" v-hasPermi="['merchant:dish:edit']">
            {{ scope.row.status === 0 ? '启售' : '停售' }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改套餐管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="套餐名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入套餐名称" />
        </el-form-item>
        <el-form-item label="菜品分类" prop="categoryId">
          <el-select v-model="form.categoryId" placeholder="请选择菜品分类">
            <el-option v-for="category in categoryList" :key="category.id" :label="category.name"
              :value="category.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="套餐价格" prop="price">
          <el-input v-model="form.price" placeholder="请输入套餐价格" />
        </el-form-item>
        <el-divider content-position="center">套餐菜品</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddSetmealDish">添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDeleteSetmealDish">删除</el-button>
          </el-col>
        </el-row>
        <el-table :data="setmealDishList" :row-class-name="rowSetmealDishIndex"
          @selection-change="handleSetmealDishSelectionChange" ref="setmealDish">
          <el-table-column type="selection" width="50" align="center" />
          <!-- <el-table-column label="序号" align="center" prop="index" width="50" /> -->
          <!-- <el-table-column label="菜品id" prop="dishId" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.dishId" placeholder="请输入菜品id" />
            </template>
          </el-table-column> -->
          <!-- <el-table-column label="菜品选择" width="200">
            <template slot-scope="scope">
              <el-button @click="showCategoryDialog(scope.row)">选择菜品</el-button>
            </template>
          </el-table-column> -->
          <!-- 修改表格列显示逻辑 -->
          <el-table-column label="菜品选择" width="200">
            <template slot-scope="scope">
              <template v-if="scope.row.name">
                {{ scope.row.name }}
              </template>
              <el-button v-else @click="showCategoryDialog(scope.row)" type="text">
                选择菜品
              </el-button>
            </template>
          </el-table-column>
          <el-table-column label="菜品份数" prop="copies" width="150">
            <template slot-scope="scope">
              <el-input-number v-model="scope.row.copies" :min="1" :controls-position="right" style="width:130px;" />
            </template>
          </el-table-column>
        </el-table>
        <el-form-item label="图片" prop="image">
          <image-upload v-model="form.image" />
        </el-form-item>
        <el-form-item label="套餐描述" prop="description">
          <el-input type="textarea" :rows="5" v-model="form.description" placeholder="请输入描述信息" style="width: 300px" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 修改后的弹窗部分 -->
    <el-dialog title="选择菜品" :visible.sync="dialogVisible" width="50%">
      <el-row>
        <!-- 左侧分类菜单 -->
        <el-col :span="6">
          <div class="category-menu">
            <div v-for="category in categoryList1" :key="category.id" class="category-item"
              :class="{ 'active': selectedCategoryId === category.id }" @click="handleCategorySelect(category.id)">
              {{ category.name }}
            </div>
          </div>
        </el-col>

        <!-- 右侧菜品列表 -->
        <el-col :span="18" class="dish-list">
          <el-table :data="currentDishes" v-loading="loading" height="400" @row-click="selectDish">
            <el-table-column label="菜品图片" width="100">
              <template slot-scope="scope">
                <image-preview :src="scope.row.image" :width="40" :height="40" />
              </template>
            </el-table-column>
            <el-table-column label="菜品名称" prop="name" />
            <el-table-column label="价格">
              <template slot-scope="scope">
                ￥{{ scope.row.price }}
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import { listSetmeal, getSetmeal, delSetmeal, addSetmeal, updateSetmeal } from "@/api/merchant/setmeal";
import { listCategory } from "@/api/merchant/category";
import { listDish } from "@/api/merchant/dish";
export default {
  name: "Setmeal",
  dicts: ['steal_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedSetmealDish: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 套餐管理表格数据
      setmealList: [],
      // 套餐菜品关系表格数据
      setmealDishList: [],
      // 套餐列表
      categoryList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        categoryId: null,
        name: null,
        status: null,
      },
      dishList: [],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        categoryId: [
          { required: true, message: "套餐分类不能为空", trigger: "blur" }
        ],
        name: [
          { required: true, message: "套餐名称不能为空", trigger: "blur" }
        ],
        price: [
          { required: true, message: "套餐价格不能为空", trigger: "blur" }
        ],
      },
      dialogVisible: false,
      currentDishes: [], // 当前分类下的菜品
      selectedRow: null, // 当前选中的表格行
      categoryList1: []
    };
  },
  created() {
    this.getCategoryList();
    this.getCategoryList1();
    this.getDishList();
    this.getList();
  },
  activated() {
    this.getCategoryList();
    this.getCategoryList1();
    this.getDishList();
    this.getList();
  },
  methods: {
    // 启用禁用按钮操作
    toggleStatus(row) {
      row.status = row.status === 0 ? 1 : 0;
      updateSetmeal(row).then(() => {
        this.$modal.msgSuccess(row.status === 1 ? '启售成功' : '停售成功');
        this.getList();
      });
    },
    // 修改添加菜品方法初始化字段
    handleAddSetmealDish() {
      this.setmealDishList.push({
        dishId: null,
        name: '',
        price: null,
        copies: 1, // 初始化默认值
        image: null
      });
    },
    // 显示弹窗
    showCategoryDialog(row) {
      this.selectedRow = row;
      this.dialogVisible = true;
      this.currentDishes = []; // 清空菜品列表
    },
    // 选择一级分类
    handleCategorySelect(categoryId) {
      this.loading = true; // 开始加载时显示加载状态
      listDish({ status: 1, categoryId: categoryId }).then(response => {
        this.currentDishes = response.rows; // 设置当前分类下的菜品列表
        this.loading = false; // 加载完成后关闭加载状态
      }).catch(() => {
        this.loading = false; // 如果请求失败，也要关闭加载状态
      });
    },
    // 修改选择菜品方法
    selectDish(dish) {
      // 直接更新当前行的数据
      Object.assign(this.selectedRow, {
        dishId: dish.id,
        name: dish.name,
        price: dish.price,
        image: dish.image,
        copies: 1 // 确保初始化份数
      });

      // 检查是否已存在相同菜品
      const exists = this.setmealDishList.some(item =>
        item.dishId === this.selectedRow.dishId
      );

      // 如果不存在则更新列表
      if (!exists) {
        this.setmealDishList = this.setmealDishList.map(item =>
          item === this.selectedRow ? this.selectedRow : item
        );
      }

      this.dialogVisible = false;
    },
    /** 查询菜品分类列表 */
    getCategoryList() {
      //只查询启用的菜品分类
      listCategory({ status: 1, type: 2 }).then(response => {
        this.categoryList = response.rows;
      });
    },
    /** 查询菜品分类列表 */
    getCategoryList1() {
      //只查询启用的菜品分类
      listCategory({ status: 1, type: 1 }).then(response => {
        this.categoryList1 = response.rows;
      });
    },
    /** 查询套餐管理列表 */
    getList() {
      this.loading = true;
      listSetmeal(this.queryParams).then(response => {
        this.setmealList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /**
     * 获取菜品列表
     */
    getDishList() {
      this.loading = true;
      listDish({ status: 1 }).then(response => {
        this.dishList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        categoryId: null,
        name: null,
        price: null,
        status: null,
        description: null,
        image: null,
        createTime: null,
        updateTime: null,
        createUser: null,
        updateUser: null
      };
      this.setmealDishList = [];
      this.resetForm("form");
    },
    getCategoryName(categoryId) {
      const category = this.categoryList.find(item => item.id === categoryId);
      return category ? category.name : '该套餐暂时停售';
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加套餐管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getSetmeal(id).then(response => {
        this.form = response.data;
        this.setmealDishList = response.data.setmealDishList;
        this.open = true;
        this.title = "修改套餐管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.setmealDishList = this.setmealDishList;
          if (this.form.id != null) {
            updateSetmeal(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addSetmeal(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除套餐管理编号为"' + ids + '"的数据项？').then(function () {
        return delSetmeal(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 套餐菜品关系序号 */
    rowSetmealDishIndex({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },
    /** 套餐菜品关系添加按钮操作 */
    handleAddSetmealDish() {
      let obj = {};
      obj.dishId = "";
      obj.name = "";
      obj.price = "";
      obj.copies = "";
      this.setmealDishList.push(obj);
    },
    /** 套餐菜品关系删除按钮操作 */
    handleDeleteSetmealDish() {
      if (this.checkedSetmealDish.length == 0) {
        this.$modal.msgError("请先选择要删除的套餐菜品关系数据");
      } else {
        const setmealDishList = this.setmealDishList;
        const checkedSetmealDish = this.checkedSetmealDish;
        this.setmealDishList = setmealDishList.filter(function (item) {
          return checkedSetmealDish.indexOf(item.index) == -1
        });
      }
    },
    /** 复选框选中数据 */
    handleSetmealDishSelectionChange(selection) {
      this.checkedSetmealDish = selection.map(item => item.index)
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('merchant/setmeal/export', {
        ...this.queryParams
      }, `setmeal_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
<style scoped>
/* 添加样式 */
.category-menu {
  border-right: 1px solid #e6e6e6;
  height: 400px;
  overflow-y: auto;
}

.category-item {
  padding: 12px 20px;
  cursor: pointer;
  transition: all 0.3s;
  border-left: 3px solid transparent;
}

.category-item:hover {
  background: #f5f7fa;
}

.category-item.active {
  border-left-color: #409eff;
  background: #ecf5ff;
}

.dish-list {
  padding-left: 20px;
}
</style>
